package com.xjuse.yida.commom.redis;

import org.redisson.api.RBucket;
import org.redisson.api.RKeys;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 杜文旭
 * @describe: RedissonClient操作封装
 * @date 2020/8/24 15:34
 */
@Component
public class RedissonUtil {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * key设置值
     * @param key 键
     * @param value 值
     */
    public void setString(String key,String value){
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.set(value);
    }

    /**
     * key设置值并指定过期时间
     * @param key 键
     * @param value 值
     */
    public void setString(String key, String value, Long time, TimeUnit unit){
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.set(value,time,unit);
    }

    /**
     * 获取值
     * @param key 键
     */
    public Object getString(String key){
        RBucket<Object> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    /**
     * 获取指定正则key
     * @param pattern
     * @return
     */
    public Iterable<String> keysByPattern(String pattern,int count){
        RKeys keys = redissonClient.getKeys();
        return keys.getKeysByPattern(pattern,count);
    }

    /**
     * 获取指定正则key
     * @param pattern
     * @return
     */
    public Iterable<String> defaultKeysByPattern(String pattern){
        RKeys keys = redissonClient.getKeys();
        return keys.getKeysByPattern(pattern);
    }

    /**
     * hSet
     * @param mapKey
     * @param key
     * @param value
     */
    public void hSet(String mapKey,String key,String value){
        RMap<Object, Object> map = redissonClient.getMap(mapKey);
        map.put(key,value);
    }

    /**
     * hGet
     * @param mapKey
     * @param key
     * @return
     */
    public String hGet(String mapKey,String key){
        RMap<Object, String> map = redissonClient.getMap(mapKey);
        return map.get(key);
    }


}